import { Button, Input, message } from 'antd'
import Form from 'antd/lib/form'
import axios from 'axios'
import React, { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { API } from '../../config'
import { isAuth } from '../../helpers/auth'
import Layout from '../core/Layout'

const AddCategory = () => {
  const [name,setName] = useState<string>('')
  const {user:{_id},token} = isAuth()
  useEffect(() => {
    async function createCategory() {
      try{
        const response = await axios.post(`${API}/category/create/${_id}`,{
          name
        },
        {
          headers: {
            Authorization: `Bearer ${token}`
          }
        })
        message.success(`[${name}] 添加成功`)
      }catch(error){
        message.error(`${error.response.data.error} 添加失败`)
      }
    }
    if (name) {
      createCategory()
    }
  }, [name])
  const onFinish = (value: {name: string}) => {
    console.log(value)
    setName(value.name)
  }
  return (
    <Layout title="添加分类" subTitle="">
      <Form onFinish={onFinish}>
        <Form.Item name="name" label="产品分类">
          <Input />
          </Form.Item>
        <Form.Item>
        <Button type="primary" htmlType="submit">添加分类</Button>
          </Form.Item>
      </Form>
      <Button>
        <Link to="/admin/dashboard">返回 DashBoard</Link>
      </Button>
    </Layout>
  )
}
export default AddCategory